package com.zhentao.datacollection.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.datacollection.domain.dto.StorageStatisticsDTO;
import com.zhentao.datacollection.domain.entity.StorageStatistics;
import com.zhentao.datacollection.mapper.StorageStatisticsMapper;
import com.zhentao.datacollection.service.StorageStatisticsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 入库统计服务实现类
 */
@Service
public class StorageStatisticsServiceImpl extends ServiceImpl<StorageStatisticsMapper, StorageStatistics> implements StorageStatisticsService {

    @Autowired
    private StorageStatisticsMapper storageStatisticsMapper;

    @Override
    public IPage<StorageStatisticsDTO> getStorageStatisticsPage(int pageNo, int pageSize,
                                                              LocalDate startDate, LocalDate endDate,
                                                              String dataType, String storageStatus) {
        Page<StorageStatistics> page = new Page<>(pageNo, pageSize);

        // 使用简化的查询，在Service层进行过滤
        IPage<StorageStatistics> statisticsPage = storageStatisticsMapper.selectPageWithConditions(
            page, startDate, endDate, dataType, storageStatus);

        // 在内存中进行过滤（临时解决方案）
        List<StorageStatistics> filteredRecords = statisticsPage.getRecords().stream()
                .filter(record -> {
                    if (startDate != null && record.getClearanceDate().isBefore(startDate)) return false;
                    if (endDate != null && record.getClearanceDate().isAfter(endDate)) return false;
                    if (dataType != null && !dataType.isEmpty() && !dataType.equals(record.getDataType())) return false;
                    if (storageStatus != null && !storageStatus.isEmpty() && !storageStatus.equals(record.getStorageStatus())) return false;
                    return true;
                })
                .collect(Collectors.toList());

        // 转换为DTO
        IPage<StorageStatisticsDTO> dtoPage = new Page<>(pageNo, pageSize, filteredRecords.size());
        List<StorageStatisticsDTO> dtoList = filteredRecords.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        dtoPage.setRecords(dtoList);

        return dtoPage;
    }

    @Override
    public Map<String, Object> getStatisticsOverview(LocalDate startDate, LocalDate endDate) {
        StorageStatistics overview = storageStatisticsMapper.getStatisticsOverview(startDate, endDate);
        
        Map<String, Object> result = new HashMap<>();
        result.put("totalRecords", overview.getRecordCount() != null ? overview.getRecordCount() : 0);
        result.put("successCount", 0); // 需要从查询结果中获取
        result.put("failedCount", 0);  // 需要从查询结果中获取
        result.put("totalRmbAmount", overview.getRmbAmount() != null ? overview.getRmbAmount() : BigDecimal.ZERO);
        result.put("totalUsdAmount", overview.getUsdAmount() != null ? overview.getUsdAmount() : BigDecimal.ZERO);
        
        return result;
    }

    @Override
    public List<String> getAllDataTypes() {
        return storageStatisticsMapper.getAllDataTypes();
    }

    @Override
    public List<StorageStatisticsDTO> exportStorageStatistics(LocalDate startDate, LocalDate endDate,
                                                             String dataType, String storageStatus,
                                                             int maxRecords) {
        List<StorageStatistics> statisticsList = storageStatisticsMapper.selectForExport(
            startDate, endDate, dataType, storageStatus, maxRecords);

        // 在内存中进行过滤
        List<StorageStatistics> filteredList = statisticsList.stream()
                .filter(record -> {
                    if (startDate != null && record.getClearanceDate().isBefore(startDate)) return false;
                    if (endDate != null && record.getClearanceDate().isAfter(endDate)) return false;
                    if (dataType != null && !dataType.isEmpty() && !dataType.equals(record.getDataType())) return false;
                    if (storageStatus != null && !storageStatus.isEmpty() && !storageStatus.equals(record.getStorageStatus())) return false;
                    return true;
                })
                .limit(maxRecords)
                .collect(Collectors.toList());

        return filteredList.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    public void calculateGrowthRates(StorageStatistics statistics) {
        if (statistics.getClearanceDate() == null || statistics.getDataType() == null) {
            return;
        }

        LocalDate clearanceDate = statistics.getClearanceDate();
        int currentYear = clearanceDate.getYear();
        int currentMonth = clearanceDate.getMonthValue();
        String dataType = statistics.getDataType();

        // 获取去年同月金额
        BigDecimal lastYearAmount = storageStatisticsMapper.getLastYearSameMonthAmount(
            currentYear - 1, currentMonth, dataType);
        statistics.setLastYearSameMonthAmount(lastYearAmount);

        // 获取上月金额
        LocalDate lastMonth = clearanceDate.minusMonths(1);
        BigDecimal lastMonthAmount = storageStatisticsMapper.getLastMonthAmount(
            lastMonth.getYear(), lastMonth.getMonthValue(), dataType);
        statistics.setLastMonthAmount(lastMonthAmount);

        // 计算同比增长率
        BigDecimal yearOnYearGrowth = calculateGrowthRate(statistics.getRmbAmount(), lastYearAmount);
        statistics.setYearOnYearGrowth(yearOnYearGrowth);

        // 计算环比增长率
        BigDecimal monthOnMonthGrowth = calculateGrowthRate(statistics.getRmbAmount(), lastMonthAmount);
        statistics.setMonthOnMonthGrowth(monthOnMonthGrowth);
    }

    @Override
    public String formatGrowthRate(StorageStatistics current, StorageStatistics lastYear, StorageStatistics lastMonth, boolean isYearOnYear) {
        BigDecimal currentAmount = current.getRmbAmount();
        BigDecimal compareAmount = isYearOnYear ? 
            (lastYear != null ? lastYear.getRmbAmount() : null) : 
            (lastMonth != null ? lastMonth.getRmbAmount() : null);

        return formatGrowthRateText(currentAmount, compareAmount);
    }

    @Override
    public void updateGrowthRates(LocalDate startDate, LocalDate endDate) {
        // 批量更新指定日期范围内的增长率
        List<StorageStatistics> statisticsList = storageStatisticsMapper.selectForExport(
            startDate, endDate, null, null, 10000);
        
        for (StorageStatistics statistics : statisticsList) {
            calculateGrowthRates(statistics);
            storageStatisticsMapper.updateById(statistics);
        }
    }

    @Override
    public void generateTestData(LocalDate startDate, LocalDate endDate) {
        Random random = new Random();
        String[] dataTypes = {"报关单", "舱单", "运单", "核注清单"};
        String[] statuses = {"SUCCESS", "FAILED"};
        
        LocalDate currentDate = startDate;
        while (!currentDate.isAfter(endDate)) {
            for (String dataType : dataTypes) {
                StorageStatistics statistics = new StorageStatistics();
                statistics.setClearanceDate(currentDate);
                statistics.setDataType(dataType);
                statistics.setStorageStatus(statuses[random.nextInt(statuses.length)]);
                
                if ("SUCCESS".equals(statistics.getStorageStatus())) {
                    statistics.setRmbAmount(BigDecimal.valueOf(random.nextDouble() * 1000000 + 100000));
                    statistics.setUsdAmount(statistics.getRmbAmount().divide(BigDecimal.valueOf(7.2), 2, RoundingMode.HALF_UP));
                } else {
                    statistics.setFailureReason("数据格式错误");
                }
                
                statistics.setRecordCount(random.nextInt(1000) + 100);
                statistics.setStorageTime(LocalDateTime.now());
                statistics.setCreatedTime(LocalDateTime.now());
                statistics.setUpdatedTime(LocalDateTime.now());
                
                calculateGrowthRates(statistics);
                storageStatisticsMapper.insert(statistics);
            }
            currentDate = currentDate.plusDays(1);
        }
    }

    /**
     * 转换为DTO
     */
    private StorageStatisticsDTO convertToDTO(StorageStatistics entity) {
        StorageStatisticsDTO dto = new StorageStatisticsDTO();
        BeanUtils.copyProperties(entity, dto);
        
        // 设置状态文本
        dto.setStorageStatusText("SUCCESS".equals(entity.getStorageStatus()) ? "成功" : "失败");
        
        // 格式化增长率文本
        dto.setYearOnYearGrowthText(formatGrowthRateText(entity.getRmbAmount(), entity.getLastYearSameMonthAmount()));
        dto.setMonthOnMonthGrowthText(formatGrowthRateText(entity.getRmbAmount(), entity.getLastMonthAmount()));
        
        return dto;
    }

    /**
     * 计算增长率
     */
    private BigDecimal calculateGrowthRate(BigDecimal current, BigDecimal previous) {
        if (current == null || previous == null) {
            return null;
        }
        
        if (previous.compareTo(BigDecimal.ZERO) == 0) {
            return current.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : null; // 表示无穷大
        }
        
        return current.subtract(previous)
                .divide(previous, 4, RoundingMode.HALF_UP)
                .multiply(BigDecimal.valueOf(100));
    }

    /**
     * 格式化增长率文本
     */
    private String formatGrowthRateText(BigDecimal current, BigDecimal previous) {
        // 根据需求文档的逻辑实现
        if (current == null && previous == null) {
            return "-"; // 均为空值
        }
        
        if (current == null) {
            return "-"; // 本月金额为空
        }
        
        if (previous == null) {
            return "-"; // 对比月份金额为空
        }
        
        if (current.compareTo(BigDecimal.ZERO) == 0 && previous.compareTo(BigDecimal.ZERO) == 0) {
            return "0%"; // 均为零
        }
        
        if (current.compareTo(BigDecimal.ZERO) == 0) {
            return "-100%"; // 仅本月为零
        }
        
        if (previous.compareTo(BigDecimal.ZERO) == 0) {
            return "+∞%"; // 仅对比月份为零
        }
        
        // 正常计算
        BigDecimal growthRate = calculateGrowthRate(current, previous);
        if (growthRate == null) {
            return "-";
        }
        
        return (growthRate.compareTo(BigDecimal.ZERO) >= 0 ? "+" : "") + 
               growthRate.setScale(2, RoundingMode.HALF_UP) + "%";
    }
}
